﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Mapping Application Block
//===============================================================================

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows;
using Messages = EntLibContrib.Mapping.QuickStart.Properties.Resources;

namespace EntLibContrib.Mapping.QuickStart
{
	/// <summary>
	/// Interaction logic for DomainObjectViewer.xaml
	/// </summary>
	public partial class DomainObjectViewer : Window
	{
		#region Construction
		public DomainObjectViewer()
		{
			InitializeComponent();
			domainObjectListBox.ItemsSource = ((App)App.Current).Basic1Collection;
			CheckCount();
			CheckStatus();
		}
		#endregion

		#region Protected Event Handlers
		protected override void OnClosing(CancelEventArgs e)
		{
 			base.OnClosing(e);
			if (!((App)App.Current).AllowShutdown())
				e.Cancel = true;
		}
		#endregion

		#region Private Event Handlers
		private void OnSave(object sender, RoutedEventArgs e)
		{
			try
			{
				if (((App)App.Current).IsDirty)
				{
					DomainObjectController.SaveChangesInBasic1Collection(((App)App.Current).Basic1Collection);
					Refresh();
					MessageBox.Show(Messages.SaveSuccess, Messages.SaveHeader, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
				}
				else
					MessageBox.Show(Messages.SaveNotNeeded, Messages.SaveHeader, MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
			}
			catch (Exception exc)
			{
				EventLog.WriteEntry("Application", exc.Message, EventLogEntryType.Error);
				MessageBox.Show(Messages.SaveFailed, Messages.SaveHeader, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
			}
		}

		private void OnRefresh(object sender, RoutedEventArgs e)
		{
			Refresh();
		}

		private void OnExit(object sender, RoutedEventArgs e)
		{
			Close();
		}

		private void OnCheckStatus(object sender, RoutedEventArgs e)
		{
			CheckStatus();
		}

		private void CheckCount()
		{
			itemCountLabel.Content = string.Format("Domain Objects: {0}", ((App)App.Current).Basic1Collection.Count);
		}

		private void Refresh()
		{
			((App)App.Current).Refresh();
			domainObjectListBox.ItemsSource = ((App)App.Current).Basic1Collection;
			CheckCount();
			CheckStatus();
		}

		private void CheckStatus()
		{
			if (((App)App.Current).IsDirty)
				saveRequiredLabel.Content = "Changed";
			else
				saveRequiredLabel.Content = "Unchanged";
		}
		#endregion
	}
}
